<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"> 
<html>
<head>
<title>Java Swing first programs</title>
<link rel="stylesheet" href="/cfg/format.css" type="text/css">
<meta http-equiv="content-type" content="text/html; charset=utf-8">
<meta name="keywords" content="Java, Swing, First programs, tutorial, programming, Linux">
<meta name="description" content="This part of the Java Swing tutorial we 
create first Java Swing programs.">
<meta name="language" content="en">
<meta name="author" content="Jan Bodnar">
<meta name="distribution" content="global">

<script type="text/javascript" src="/lib/jquery.js"></script>
<script type="text/javascript" src="/lib/common.js"></script>

</head>

<body>

<div class="container">

<div id="wide_ad" class="ltow">
<script type="text/javascript"><!--
google_ad_client = "pub-9706709751191532";
/* 160x600, August 2011 */
google_ad_slot = "2484182563";
google_ad_width = 160;
google_ad_height = 600;
//-->
</script>
<script type="text/javascript"
src="http://pagead2.googlesyndication.com/pagead/show_ads.js">
</script>
</div>

<div class="content">


<a href="/" title="Home">Home</a>&nbsp;
<a href=".." title="Home">Contents</a>


<h1>Java Swing first programs</h1>


<p>
In this chapter, we will program our first programs in Swing toolkit. 
The examples are going to be very simple.
We will cover some basic functionality.
</p>

<script type="text/javascript"><!--
google_ad_client = "pub-9706709751191532";
/* NewSquare */
google_ad_slot = "0364418177";
google_ad_width = 300;
google_ad_height = 250;
//-->
</script> 
<script type="text/javascript"
src="http://pagead2.googlesyndication.com/pagead/show_ads.js"> 
</script>


<h2>Our first example</h2>


<p>
In our first example, we will show a basic window on the screen. 
</p>

<pre class="code">
package zetcode;

import javax.swing.JFrame;
import javax.swing.SwingUtilities;

public class Example extends JFrame {

    public Example() {
       setTitle("Simple example");
       setSize(300, 200);
       setLocationRelativeTo(null);
       setDefaultCloseOperation(EXIT_ON_CLOSE);
    }

    public static void main(String[] args) {
        SwingUtilities.invokeLater(new Runnable() {
            public void run() {
                Example ex = new Example();
                ex.setVisible(true);
            }
        });
    }
}
</pre>

<p>
While this code is very small, the application window can do quite a lot. 
It can be resized, maximized, minimized. All the complexity that comes 
with it has been hidden from the application programmer. 
</p>

<pre class="explanation">
import javax.swing.JFrame;
import javax.swing.SwingUtilities;
</pre>

<p>
Here we import Swing classes, that will be used in the code example.
</p>

<pre class="explanation">
public class Example extends JFrame {
</pre>

<p>
The Example class inherits from the <code>JFrame</code> widget. <code>JFrame</code>
is a toplevel container, which is used for placing other widgets. 
</p>

<pre class="explanation">
setTitle("Simple example");
</pre>

<p>
Here we set the title of the window using the <code>setTitle()</code>
method.
</p>

<pre class="explanation">
setSize(300, 200);
</pre>

<p>
This code will resize the window to be 300px wide and 200px tall. 
</p>

<pre class="explanation">
setLocationRelativeTo(null);
</pre>

<p>
This line will center the window on the screen.
</p>


<pre class="explanation">
setDefaultCloseOperation(EXIT_ON_CLOSE);
</pre>

<p>
This method will close the window, if we click on the close button of the
titlebar. By default nothing happens.
</p>

<pre class="explanation">
SwingUtilities.invokeLater(new Runnable() {
    public void run() {
        Example ex = new Example();
        ex.setVisible(true);
    }
});
</pre>

<p>
We create an instance of our code example and make it visible on 
the screen. The <code>invokeLater()</code> method places
the application on the Swing Event Queue. It is used to ensure 
that all UI updates are concurrency-safe. In other words, it
is to prevent GUI from hanging in certain situations. This topic
is an advanced concept and we should not worry right now about
it. 
</p>

<img src="/img/gui/javaswing/simple.png" alt="Simple example">
<div class="figure">Figure: Simple example</div>



<h2>Quit button</h2>

<p>
In our next example, we will have a button. When we click on the button,
the application terminates. 
</p>


<pre class="code">
package zetcode;

import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;

import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.SwingUtilities;


public class Example extends JFrame {

    public Example() {
        initUI();
    }

    public final void initUI() {

       JPanel panel = new JPanel();
       getContentPane().add(panel);

       panel.setLayout(null);

       JButton quitButton = new JButton("Quit");
       quitButton.setBounds(50, 60, 80, 30);
       quitButton.addActionListener(new ActionListener() {
           public void actionPerformed(ActionEvent event) {
               System.exit(0);
          }
       });

       panel.add(quitButton);

       setTitle("Quit button");
       setSize(300, 200);
       setLocationRelativeTo(null);
       setDefaultCloseOperation(EXIT_ON_CLOSE);
    }

    public static void main(String[] args) {
        SwingUtilities.invokeLater(new Runnable() {
            public void run() {
                Example ex = new Example();
                ex.setVisible(true);
            }
        });
    }
}
</pre>

<p>
We position a <code>JButton</code> on the window. We will add an action listener
to this button.
</p>

<pre class="explanation">
public Example() {
    initUI();
}
</pre>

<p>
It is a good programming practice to put the code that creates the GUI
inside a specific method. 
</p>

<pre class="explanation">
JPanel panel = new JPanel();
getContentPane().add(panel);
</pre>

<p>
We create a <code>JPanel</code> component. It is a generic lightweight 
container. We add the JPanel to the <code>JFrame</code>. 
</p>

<pre class="explanation">
panel.setLayout(null);
</pre>

<p>
By default, the JPanel has a <code>FlowLayout</code> manager. The layout
manager is used to place widgets onto the 
containers. If we call <code>setLayout(null)</code> we can position our 
components absolutely. For this, we use the 
<code>setBounds()</code> method.
</p>

<pre class="explanation">
JButton quitButton = new JButton("Quit");
quitButton.setBounds(50, 60, 80, 30);
quitButton.addActionListener(new ActionListener() {
    public void actionPerformed(ActionEvent event) {
        System.exit(0);
  }
});
</pre>

<p>
Here we create a button. We position it by calling the <code>setBounds()</code> 
method. Then we add an action listener.
The action listener will be called, when we perform an action on the button. 
In our case, if we click on the button.
The click will terminate the application.
</p>

<pre class="explanation">
panel.add(quitButton);
</pre>

<p>
In order to show the quit button, we must add it to the panel. 
</p>

<img src="/img/gui/javaswing/quitbutton.png" alt="Quit button">
<div class="figure">Figure: Quit button</div>


<h2>A tooltip</h2>

<p>
Tooltips are part of the internal application's help system. The Swing 
shows a small rectangular window, if we hover a mouse
pointer over an object. 
</p>


<pre class="code">
package zetcode;

import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.SwingUtilities;


public class Example extends JFrame {

    public Example() {
        initUI();
    }

    public final void initUI() {

        JPanel panel = new JPanel();
        getContentPane().add(panel);

        panel.setLayout(null);
        panel.setToolTipText("A Panel container");

        JButton button = new JButton("Button");
        button.setBounds(100, 60, 100, 30);
        button.setToolTipText("A button component");

        panel.add(button);

        setTitle("Tooltip");
        setSize(300, 200);
        setLocationRelativeTo(null);
        setDefaultCloseOperation(EXIT_ON_CLOSE);
    }

    public static void main(String[] args) {
        SwingUtilities.invokeLater(new Runnable() {
            public void run() {
                Example ex = new Example();
                ex.setVisible(true);
            }
        });
    }
}
</pre>


<p>
In the example, we set the tooltip for the frame and the button.
</p>

<pre class="explanation">
panel.setToolTipText("A Panel container");
</pre>

<p>
To enable a tooltip, we call the <code>setTooltipText()</code> method.
</p>


<img src="/img/gui/javaswing/tooltip.png" alt="Tooltip">
<div class="figure">Figure: Tooltip</div>


<p>
In this chapter, we have created some simple Java Swing programs.
</p>


<div class="center"> 
<script type="text/javascript"><!--
google_ad_client = "pub-9706709751191532";
/* horizontal */
google_ad_slot = "1734478269";
google_ad_width = 468;
google_ad_height = 60;
//-->
</script> 
<script type="text/javascript"
src="http://pagead2.googlesyndication.com/pagead/show_ads.js"> 
</script> 
</div>  
<br>


<div class="botNav, center">
<span class="botNavItem"><a href="/">Home</a></span> ‡ <span class="botNavItem"><a href="..">Contents</a></span> ‡ 
<span class="botNavItem"><a href="#">Top of Page</a></span>
</div>

<div class="footer">
<div class="signature">
<a href="/">ZetCode</a> last modified December 4, 2010  <span class="copyright">&copy; 2007 - 2013 Jan Bodnar</span>
</div>
</div>

</div> <!-- content -->

</div> <!-- container -->

</body>
</html>

